package nz.ac.massey.webtech.chat;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Fetch messages for the conversation this client is part of. 
 * Messages are JSOn encoded.
 * @author jens dietrich
 */
public class GetMessages extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/event-stream");
        response.setCharacterEncoding ("UTF-8");
        List<Message> messages = ConversationManager.fetchMessages(request.getSession());
        
        PrintWriter out = response.getWriter();
        //out.append("retry: 1000\n");
        out.append("event: message\n");
        out.append("data:");
        
        // json encode messages
        out.append('[');
        boolean first = true;
        for (Message message:messages) {
            if (first) first=false;
            else out.append(',');
            out.append(message.toJSON());
        }
        out.append(']');
        
        out.append("\n\n");
        response.flushBuffer();
    }

    @Override
    public String getServletInfo() {
        return "fetch a message";
    }
}
